package com.bjgov.scoresys.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpUtil {
	private static final Log log = LogFactory
			.getLog(HttpUtil.class);

	public static String send(String url, String param, String method) {
		String result = "";
		URL urlCon = null;
		url = url + (StringUtils.isEmpty(param) ? "" : "?" + param);
		HttpURLConnection httpconn = null;
		try {
			urlCon = new URL(url);
			URLConnection URLconnection = urlCon.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) URLconnection;
			httpConnection.setConnectTimeout(10000);
			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream urlStream = httpConnection.getInputStream();
				BufferedReader bufferedReader = new BufferedReader(
						new InputStreamReader(urlStream));
				String sCurrentLine = "";
				String sTotalString = "";
				while ((sCurrentLine = bufferedReader.readLine()) != null) {
					sTotalString += sCurrentLine;
				}
				result = sTotalString;
			} else {
				result = "发送数据出错，远程服务返回值：" + responseCode;
			}
		} catch (Exception e) {
			log.error("连接出错：url=" + url, e);
			result = "连接远程服务失败!";
		} finally {
			if (httpconn != null) {
				httpconn.disconnect();
			}
		}
		log.info("send(" + url + ") return=" + result);
		return result;
	}
}
